﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Camelot.SharePointIntegration.IntegrationService
{
    public sealed class ServiceConfigurationReader
    {
        private ServiceConfigurationReader() {}

        public static Entities.Configuration ReadXml(string file)
        {
            if (!File.Exists(file))
                throw new FileNotFoundException("Configuration file could not be found", file);

            var xmlValidator = new XmlValidator();
            var xmlDoc = xmlValidator.LoadXml(file, Properties.Resources.ServiceConfiguration);

            if (!xmlValidator.IsValid)
                throw new Exception(xmlValidator.ErrorMessage);

            return (Entities.Configuration)Deserialize(xmlDoc, typeof(Entities.Configuration));
        }

        public static string WriteXml(Entities.Configuration configuration)
        {
            return Serialize(configuration);
        }

        private static object Deserialize(XmlNode xmlNode, Type type)
        {
            var xmlSerializer = new XmlSerializer(type);
            var xmlNodeReader = new XmlNodeReader(xmlNode);
            return xmlSerializer.Deserialize(xmlNodeReader);
        }

        private static string Serialize(object obj)
        {
            var xmlSerializer = new XmlSerializer(obj.GetType());
            using (var ms = new System.IO.MemoryStream())
            {
                xmlSerializer.Serialize(ms, obj);
                return System.Text.Encoding.UTF8.GetString(ms.ToArray());
            }
        }
    }
}
